<template>
  <div class="rule-box">
    <div v-if="$route.query.name" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div class="app-container hk-flex-column">
      <div class="app-container-bg">
        <TypeItem :tabs="tabs" />
      </div>
      <div class="hk-container">
        <div class="hk-flex-bottom">
          <HkSearchform
            :data="queryParams"
            :field-list="filterInfo.fieldList"
            :list-type-info="dictList"
            @handleSearch="handleQuery"
            @handleReset="handleReset"
            @handleEvent="handleEvent" />
          <el-row>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleUpdate">新增自定义规则</el-button>
            <el-button size="mini" @click="handleImport">导入</el-button>
            <el-button size="mini" :disabled="ids.length == 0" @click="handleExport">导出</el-button>
          </el-row>
        </div>

        <hk-table
          ref="tableRef"
          :loading="loading"
          :table-data="tableData"
          :table-columns="tableList"
          :selection="true"
          :show-index="true"
          :total="total"
          :operate="true"
          :table-height="80"
          show-overflow-tooltip
          :operate-width="130"
          :query-params="queryParams"
          @handleSelectionChange="handleSelectionChange"
          @changePage="getListData">
          <template #status="scope">
            <el-switch
              v-model="scope.row.status"
              class="switchStyle"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => changeStatus(val, scope.row)" />
          </template>
          <template #analyseType="scope">
            <img
              v-if="scope.row.analyseType == 1"
              class="img-icon"
              :src="
                sideTheme == 'tech' || sideTheme == 'theme-dark'
                  ? require('@/assets/images/icp/rule/dark-fenxi-sxfs-1.png')
                  : require('@/assets/images/icp/rule/fenxi-sxfs-1.png')
              "
              alt="" />
            <img
              v-if="scope.row.analyseType == 2"
              class="img-icon"
              :src="
                sideTheme == 'tech' || sideTheme == 'theme-dark'
                  ? require('@/assets/images/icp/rule/dark-fenxi-sxfs-2.png')
                  : require('@/assets/images/icp/rule/fenxi-sxfs-2.png')
              "
              alt="" />
            <img
              v-if="scope.row.analyseType == 3"
              class="img-icon"
              :src="
                sideTheme == 'tech' || sideTheme == 'theme-dark'
                  ? require('@/assets/images/icp/rule/dark-fenxi-sxfs-3.png')
                  : require('@/assets/images/icp/rule/fenxi-sxfs-3.png')
              "
              alt="" />
            {{ getDictDataName(dictList.analyseTypeList, scope.row.analyseType) }}
          </template>
          <template #ruleType="scope">
            <img
              v-if="scope.row.ruleType == 1"
              class="img-icon"
              :src="
                sideTheme == 'tech' || sideTheme == 'theme-dark'
                  ? require('@/assets/images/icp/rule/dark-fenxi-gzlx-1.png')
                  : require('@/assets/images/icp/rule/fenxi-gzlx-1.png')
              "
              alt="" />
            <img
              v-if="scope.row.ruleType == 2"
              class="img-icon"
              :src="
                sideTheme == 'tech' || sideTheme == 'theme-dark'
                  ? require('@/assets/images/icp/rule/dark-fenxi-gzlx-2.png')
                  : require('@/assets/images/icp/rule/fenxi-gzlx-2.png')
              "
              alt="" />
            {{ getDictDataName(dictList.ruleTypeList, scope.row.ruleType) }}
          </template>
          <template #operate="scope">
            <div style="display: flex">
              <el-button size="mini" :disabled="scope.row.dataType == 1" type="text" @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.ruleType == 2 && scope.row.status == 0"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
              <!--              <el-button size="mini" type="text" @click="openWhiteList(scope.row)">白名单</el-button>-->
            </div>
          </template>
        </hk-table>
      </div>
    </div>
    <!-- 新增和编辑的对话框 -->
    <edit-dialog ref="editDialogRef" :title="title" :transfer-id="transferId" @handleAdd="getListData" />
    <!-- 白名单对话框 -->
    <panel-dialog ref="panelRef" :transfer-id="transferId" :kpi-code="kpiCode" />
    <import-dialog ref="import_dia" @submit="getListData" />
  </div>
</template>

<script>
import TypeItem from './component/typeItem.vue'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import HkTable from '@/components/Hk-Table/index.vue'
import EditDialog from './component/editDialog.vue'
import { entityTree, queryPageList, editRuleStatus, deleteByid, queryCountData } from '@/api/icp/labelClassDisplay'
import panelDialog from './component/panelDialog.vue'
import importDialog from './component/importDialog.vue'
import HkSearchform from '@/components/HkSearchform/index.vue'

export default {
  name: 'IcpRule',
  components: { HkTable, EditDialog, panelDialog, importDialog, HkSearchform, TypeItem },
  beforeRouteLeave(to, from, next) {
    from.meta.keepAlive = false
    next()
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 传输的id
      transferId: '',
      // 传输的kpi_code
      kpiCode: '',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 搜索项配置
      filterInfo: {
        fieldList: [
          { label: '关键字', type: 'input', field: 'name', placeholder: '请输入规则名称/指标名称', maxlength: 20 },
          { label: '实现方式', type: 'select', field: 'analyseType', list: 'analyseTypeList' },
          { label: '状态', type: 'select', field: 'status', list: 'statusList' },
          { label: '规则类型', type: 'select', field: 'ruleType', list: 'ruleTypeList' },
        ],
      },
      dictList: {
        statusList: [
          {
            label: '关闭',
            value: '0',
          },
          {
            label: '开启',
            value: '1',
          },
        ],
        ruleTypeList: [
          {
            label: '预置',
            value: 1,
          },
          {
            label: '自定义',
            value: 2,
          },
        ],
        analyseTypeList: [
          {
            label: '触发分析',
            value: 1,
          },
          {
            label: '聚合分析',
            value: 2,
          },
          {
            label: '时序分析',
            value: 3,
          },
        ],
      },
      tabs: {
        total: 0,
        analyseTypeCount: [
          { name: '触发分析规则', type: '1', num: 0 },
          { name: '聚合分析规则', type: '2', num: 0 },
          { name: '时序分析规则', type: '3', num: 0 },
        ],
        status: [
          { name: '启用状态', type: '1', num: 0 },
          { name: '关闭状态', type: '0', num: 0 },
        ],
        ruleType: [
          { name: '预置', type: '1', num: 0 },
          { name: '自定义', type: '2', num: 0 },
        ],
      },
      // 总条数
      total: 0,
      // 表格数据
      tableData: [{}],
      //  表格
      tableList: [
        { label: '规则名称', param: 'name' },
        { label: '指标名称', param: 'metricsName' },
        { label: '实现方式', param: 'analyseType', type: 'slot', width: 240 },
        { label: '状态', param: 'status', type: 'slot', width: 150 },
        { label: '规则类型', param: 'ruleType', type: 'slot', width: 150 },
      ],
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,

      defaultProps: {
        children: 'children',
        label: 'aliasName',
      },

      // 查询参数
      queryParams: {
        size: 10,
        current: 1,
        name: '',
        status: undefined,
        analyseType: undefined,
      },
    }
  },
  computed: {
    sideTheme() {
      return this.$store.state.settings.sideTheme
    },
  },
  activated() {
    this.getCountData()
    this.getListData()
  },
  mounted() {
    this.getCountData()
    this.getListData()
    // this.getTreeselect()
    this.queryParams.name =
      this.$route.query.name === 'icpHome' ? '' : this.$route.query.name ? this.$route.query.name : ''
  },
  methods: {
    getDictDataName(dictList, value) {
      return dictList.find((o) => o.value === value)?.label
    },
    // 修改状态值
    changeStatus(val, scope) {
      const obj = {
        id: scope.id,
        status: scope.status,
        analyseType: scope.analyseType,
      }

      editRuleStatus(obj).then((res) => {
        this.$message.success('修改成功')
      })
    },
    /** 查询用户列表 */
    getListData(val) {
      this.loading = true
      this.queryParams = { ...this.queryParams, ...val, scrollToTop: true }

      queryPageList(this.queryParams).then((res) => {
        this.total = res.total
        this.tableData = res.list
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    /**
     * 获取页面上方统计数据
     */
    getCountData() {
      queryCountData().then((res) => {
        this.tabs.total = res.total
        this.tabs.analyseTypeCount.forEach((data) => {
          data.num = res.analyseTypeCount.find((o) => data.type === o.type)?.count || 0
        })
        this.tabs.status.forEach((data) => {
          data.num = res.statusCount.find((o) => data.type === o.type)?.count || 0
        })
        this.tabs.ruleType.forEach((data) => {
          data.num = res.ruleTypeCount.find((o) => data.type === o.type)?.count || 0
        })
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect(id) {
      //  this.deptOptions = treeselect;\
      entityTree(id).then((res) => {
        this.deptOptions = res
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.current = 1
      this.queryParams.size = 10
      this.getListData({ aliasType: data.name })
    },

    /** 搜索按钮操作 */
    handleQuery(val) {
      this.queryParams.current = 1
      this.getListData()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        current: 1,
        size: 10,
        name: '',
        status: undefined,
        analyseType: undefined,
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 搜索框变化
    handleEvent(val) {
      const field = val.field
      const value = val.value
      this.queryParams = {
        ...this.queryParams,
        ...{
          [field]: value,
        },
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      // props传参出现延迟
      return new Promise((resolve, reject) => {
        this.transferId = ''
        this.title = '新增'
        resolve()
      }).then(() => {
        this.$refs.editDialogRef.show()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row) {
        this.$router.push({ path: window.prefix + '/icp/ruleDetail', query: { id: row.id } })
        this.transferId = row.id
      } else {
        this.$router.push({ path: window.prefix + '/icp/ruleDetail' })
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function () {
          return deleteByid(id)
        })
        .then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getListData()
        })
        .catch((error) => {
          // console.log(error)
        })
    },
    // 打开白名单
    openWhiteList(row) {
      return new Promise((resolve, reject) => {
        this.transferId = row.id
        this.kpiCode = row.kpiCode
        resolve(this.transferId)
      }).then((res) => {
        this.$refs.panelRef.show()
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.gDownload(
        window.baseUrl.icp + '/rule/exportZip',
        { ids: this.ids.join(',') },
        `rule_${new Date().getTime()}.zip`
      )
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import_dia.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}`user_template_${new Date().getTime()}.xlsx`)
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .content {
  padding-bottom: 0 !important;
  flex: 1;
}
.img-icon {
  width: 18px;
  vertical-align: middle;
  margin-right: 5px;
}
.back-title {
  line-height: 40px;
  height: 40px;
  border-bottom: 1px solid #e9e9e9;
  // color: #989a9c;
  // margin-bottom: 10px;
}

.rule-box {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.total-box {
  flex: 1;
  display: flex;
  width: 100%;
  height: 100%;
}

.head-container {
  overflow: auto;
  padding: 20px;
  height: 100%;
  width: 270px;
  border-right: 1px solid rgba(0, 0, 0, 0.08);
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.app-container {
  padding: 0 !important;
  width: 100%;
  overflow: hidden !important;
  background: #eef0f5 !important;
}
.hk-container {
  background: #fff;
  width: 100% !important;
  overflow: hidden;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  border-radius: 4px;
}
.el-col {
  height: 100%;
  display: flex;
  flex-direction: column;

  &::v-deep .targetTable {
    flex: 1;
    // overflow: auto;
  }
}

::v-deep {
  .switchStyle .el-switch__label--right {
    left: 5px;
    top: 0;
  }

  .switchStyle .el-switch__label--left {
    top: 0;
  }
  &.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 40px !important;
  }

  div.cell {
    white-space: nowrap;
  }
  .el-table {
    margin-top: 0;
  }
  .el-table .cell {
    padding-left: 0;
  }
}
</style>
